package org.altervista.cp.microkernel.persistence.spi;

import java.io.InputStream;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Date;

public class JDBCType {

	public JDBCType(int type) {
		_type = type;
	}

	public JDBCType(Class<?> c) {
		if (CharSequence.class.isAssignableFrom(c))
			_type = Types.VARCHAR;
		else if (Character.class.isAssignableFrom(c))
			_type = Types.CHAR;
		else if (Boolean.class.isAssignableFrom(c))
			_type = Types.BOOLEAN;
		else if (Number.class.isAssignableFrom(c))
			_type = Types.NUMERIC;
		else if (Timestamp.class.isAssignableFrom(c))
			_type = Types.TIMESTAMP;
		else if (Time.class.isAssignableFrom(c))
			_type = Types.TIME;
		else if (Date.class.isAssignableFrom(c))
			_type = Types.TIMESTAMP;
		else if (Blob.class.isAssignableFrom(c))
			_type = Types.BLOB;
		else if (Clob.class.isAssignableFrom(c))
			_type = Types.CLOB;
		else if (InputStream.class.isAssignableFrom(c))
			_type = Types.BINARY;
		else
			_type = Types.OTHER;
	}

	public Object parse(Object value) {
		if (value == null)
			return null;
		if (Types.TIMESTAMP == _type) {
			Date date = (Date) value;
			return date instanceof Timestamp ? date : new Timestamp(date
					.getTime());
		}
		if (Types.BLOB == _type) {
			if (value instanceof Blob) {
				return value;
			}
			if (value instanceof InputStream) {
				return ((BlobInputStream) value).toBlob();
			}
		}
		return value;
	}

	public int getType() {
		return _type;
	}

	private int _type;

}
